﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EEG_NIRS_Record
{
    class IIRFilter
    {
        double[] ac = null;
        double[] bc = null;
        double[] m_Memory_Buffer = null;
        int m_Length_a;
        int m_Length_b;
        int m_Memory_Length;
        const int coefficients_len = 6;
        public IIRFilter()
        {
            ac = new double[coefficients_len] { 1, -4.95142697015, 9.806885460274, -9.712076954436, 4.809205570838, -0.9525871057826 };
            bc = new double[coefficients_len] { 2.324004050818e-11, 1.162002025409e-10, 2.324004050818e-10, 2.324004050818e-10, 1.162002025409e-10, 2.324004050818e-11 };
            m_Memory_Buffer = new double[coefficients_len];
            m_Length_a = coefficients_len;
            m_Length_b = coefficients_len;
            m_Memory_Length = coefficients_len;
        }
        public double IIR_Filter(double Input_Data)
        {
            int Count;
            double Output_Data = 0;

            Output_Data += ac[0] * Input_Data;  //a(0)*x(n)             

            for (Count = 1; Count < m_Length_a; Count++)
            {
                Output_Data -= ac[Count] * m_Memory_Buffer[m_Memory_Length - 1 - Count];
            }

            //------------------------save data--------------------------// 
            m_Memory_Buffer[m_Memory_Length - 1] = Output_Data;
            Output_Data = 0;
            //----------------------------------------------------------// 

            for (Count = 0; Count < m_Length_b; Count++)
            {
                Output_Data += bc[Count] * m_Memory_Buffer[m_Memory_Length - 1 - Count];
            }

            //------------------------move data--------------------------// 
            for (Count = 0; Count < m_Memory_Length - 1; Count++)
            {
                m_Memory_Buffer[Count] = m_Memory_Buffer[Count + 1];
            }
            m_Memory_Buffer[m_Memory_Length - 1] = 0;
            //-----------------------------------------------------------//

            return Output_Data;
        }
    }
}
